package com.simplehire.controller;

import com.simplehire.model.User;
import com.simplehire.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 首页
     */
    @GetMapping("/")
    public String home() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) {
            return "redirect:/interview";
        }
        return "redirect:/login";
    }

    /**
     * 显示登录页面
     */
    @GetMapping("/login")
    public String showLoginForm(Model model,
                               @RequestParam(value = "error", required = false) String error,
                               @RequestParam(value = "logout", required = false) String logout) {
        
        // 如果用户已登录，重定向到面试页面
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) {
            return "redirect:/interview";
        }

        if (error != null) {
            model.addAttribute("error", "用户名或密码错误，请重试。");
        }
        
        if (logout != null) {
            model.addAttribute("message", "您已成功退出登录。");
        }
        
        return "login";
    }

    /**
     * 显示注册页面
     */
    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        // 如果用户已登录，重定向到面试页面
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getName())) {
            return "redirect:/interview";
        }
        
        model.addAttribute("user", new User());
        return "register";
    }

    /**
     * 处理用户注册
     */
    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") User user,
                              BindingResult bindingResult,
                              @RequestParam("confirmPassword") String confirmPassword,
                              Model model,
                              RedirectAttributes redirectAttributes) {
        
        // 验证表单数据
        if (bindingResult.hasErrors()) {
            return "register";
        }
        
        // 验证密码确认
        if (!user.getPassword().equals(confirmPassword)) {
            model.addAttribute("error", "密码和确认密码不匹配。");
            return "register";
        }
        
        try {
            // 注册用户
            userService.registerUser(
                user.getUsername(),
                user.getPassword(),
                user.getEmail(),
                user.getFullName()
            );
            
            redirectAttributes.addFlashAttribute("message", 
                "注册成功！请使用您的用户名和密码登录。");
            return "redirect:/login";
            
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "register";
        }
    }

    /**
     * 检查用户名是否可用（AJAX接口）
     */
    @GetMapping("/api/check-username")
    @ResponseBody
    public boolean checkUsername(@RequestParam String username) {
        return userService.isUsernameAvailable(username);
    }

    /**
     * 检查邮箱是否可用（AJAX接口）
     */
    @GetMapping("/api/check-email")
    @ResponseBody
    public boolean checkEmail(@RequestParam String email) {
        return userService.isEmailAvailable(email);
    }

    /**
     * 用户个人资料页面
     */
    @GetMapping("/profile")
    public String showProfile(Model model, Authentication authentication) {
        User currentUser = (User) authentication.getPrincipal();
        model.addAttribute("user", currentUser);
        return "profile";
    }

    /**
     * 更新用户个人资料
     */
    @PostMapping("/profile")
    public String updateProfile(@Valid @ModelAttribute("user") User user,
                               BindingResult bindingResult,
                               Authentication authentication,
                               Model model,
                               RedirectAttributes redirectAttributes) {
        
        if (bindingResult.hasErrors()) {
            return "profile";
        }
        
        try {
            User currentUser = (User) authentication.getPrincipal();
            
            // 只更新允许修改的字段
            currentUser.setFullName(user.getFullName());
            currentUser.setEmail(user.getEmail());
            
            userService.updateUser(currentUser);
            
            redirectAttributes.addFlashAttribute("message", "个人资料更新成功！");
            return "redirect:/profile";
            
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            return "profile";
        }
    }
}